package cn.kgc.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.kgc.annotation.LoginType;
import cn.kgc.annotation.RequireLogin;
import cn.kgc.base.SystemConstant;
import cn.kgc.entity.Orders;
import cn.kgc.excpetion.GraceException;
import cn.kgc.feign.UserFeignClient;
import cn.kgc.form.OrdersAddForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.OrdersService;
import cn.kgc.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author YC
 */
@RestController
@RequestMapping("/orders")
@Api(tags = "订单支付模块")
@Slf4j
public class OrdersController {

    @Resource
    private UserFeignClient userFeignClient;
    @Resource
    private OrdersService ordersService;
    @Resource
    private WxPayService wxPayService;

    @PostMapping("/create")
    @ApiOperation(value = "创建支付订单")
    @RequireLogin(value = LoginType.USER_SAAS_LOGIN)
    public GraceJSONResult saveOrder(OrdersAddForm form) {
        String saasLoginUserId = JwtInterceptor.userIds.get();
        if (saasLoginUserId == null) {
            GraceException.display(ResponseStatusEnum.UN_LOGIN);
        }
        // 远程调用，获取公司ID
        Object data = userFeignClient.getCompanyIdByUserId(saasLoginUserId).getData();
        String companyId = (String) data;
        if (StrUtil.isBlank(companyId)) {
            return GraceJSONResult.errorMsg("创建订单失败");
        }
        form.setUserId(saasLoginUserId);
        form.setCompanyId(companyId);
        return GraceJSONResult.ok(ordersService.insertOrder(form));
    }

    @PostMapping("/isVip")
    @ApiOperation("判断是否是会员")
    public GraceJSONResult isVip() {
        //企业端扫码登录的用户ID
        String sassLoginUserId = JwtInterceptor.userIds.get();
        //根据用户的ID获得公司的信息
        Object data = userFeignClient.getCompanyIdByUserId(sassLoginUserId).getData();
        String companyId = (String) data;
        if (StrUtil.isBlank(companyId)) {
            return GraceJSONResult.errorMsg("判断是否是会员失败");
        }
        //判断是否是会员
        return GraceJSONResult.ok(ordersService.isVip(companyId));
    }

    @PostMapping("/createQr")
    @ApiOperation(value = "生成二维码（URL）")
    public GraceJSONResult createQr(String orderId) {
        // 前端获取到二维码地址后通过工具生成二维码
        Orders orders = ordersService.getById(orderId);
        if (orders == null || orders.getStatus().equals(SystemConstant.SUCCESS_PAY)) {
            return GraceJSONResult.errorMsg("订单不存在或已支付");
        }
        // 支付金额 单位：分
        Integer totalAmount = orders.getTotalAmount();
        return GraceJSONResult.ok();
    }

    @PostMapping("/pay/notify")
    @ApiOperation(value = "微信支付回调方法")
    public String handleNotify(@RequestBody String body, HttpServletRequest request) {
        try {
            // 1. 验证签名
            JSONObject data = new JSONObject(body);
            String orderId = data.getStr("out_trade_no");
            String tradeState = data.getStr("trade_state");
            // 2. 校验支付状态
            if ("SUCCESS".equals(tradeState)) {
                int paidAmount = data.getJSONObject("amount").getInt("total");
                // 更新订单状态
                ordersService.rechargeSuccess(orderId);
                return "{\"code\":\"SUCCESS\", \"message\":\"处理成功\"}";
            }
        } catch (Exception e) {
            log.error("回调处理失败: {}", e.getMessage());
        }
        return "{\"code\":\"FAIL\"}";
    }

}
